<?php
/**
 *  The default order of searching for template files:
 *  - site templates directory (lib/templates), "moduleName-tplName"
 *  - current module
 *  - parent module, parent of parent etc
 *  - Yz/templates
 *  See the $templatePath variable
 *
 */
abstract class Yz_Template_Native
    extends Yz_Template_Abstract
    implements Yz_Template_Interface
{

    /** Override the default filename for the template
     *  @var string|null
     */
    protected $filename;



    protected function doRender()
    {
        debug();

        $name = null === $this->filename
            ? $this->name()
            : $this->filename;

        $file = $this->findTemplate($name);
        extract($this->value, EXTR_PREFIX_ALL, 'var');
        ob_start();
        include("$file");
        return ob_get_clean();
    }

    /**
     *  @todo search lib/templates for {module}-{name}.php or lib/templates/{module}/ ???
     *  @return Yz_File
     *  @throw template-not-found
     */
    protected function findTemplate($name)
    {
        debug();

        $file = new Yz_File( 'templates/' . $name . '.php');
        if ($file->isFile()) {
            return $file;
        }

        $class = $this;
        while ($ns = $class::namespaceName()) {
            $path = strtr($ns, '\\', '/');
            $file = new Yz_File( $path . '/templates/' . $name . '.php');
            if ($file->isFile()) {
                return $file;
            }
            $class = get_parent_class($class);
            assert('is_subclass_of($class,"Yz_Template_Interface")');
        }
        $ex = new Yz_Template_Exception();
        throw $ex->withArgs(array("name"=>$name));
    }


    /**
     *
     *  @return Yz_File|null
     */
    protected function findTemplateRecursive()
    {
        return $file;
    }

}
